package com.whiteblue.controller;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;
import com.whiteblue.interceptor.AdminInterceptor;
import com.whiteblue.interceptor.LoginInterceptor;
import com.whiteblue.model.Post;
import com.whiteblue.model.Topic;
import com.whiteblue.validator.PostValidator;

public class PostController extends Controller {
	public void index() {
		int topicID = getParaToInt(0);
		Page<Post> postPage = Post.dao.getPage(topicID, getParaToInt(1, 1));
		setAttr("postPage", postPage);
		setAttr("topic", Topic.dao.get(topicID));
		render("/post.html");
	}

	@Before({ LoginInterceptor.class, PostValidator.class })
	public void save() {
		Post post = getModel(Post.class);
		post.set("userID", getSessionAttr("userID")).mySave();
		redirect("/post/" + post.getInt("topicID"));
	}

	@Before(AdminInterceptor.class)
	public void edit() {
		setAttr("post", Post.dao.get(getParaToInt(0)));
		render("/post/edit.html");
	}

	@Before(AdminInterceptor.class)
	public void delete() {
		Post.dao.deleteByID(getParaToInt(0));
		forwardAction("/admin/postList/" + getParaToInt(1));
	}

	@Before({ AdminInterceptor.class, PostValidator.class })
	public void update() {
		Post post = getModel(Post.class);
		post.myUpdate();
		redirect("/topic/" + post.get("topicID"));
	}
}
